package com.mbc.common.dao;

import java.util.HashMap;
import java.util.Properties;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class DBManagerFactory {
	private static HashMap<String, String> dataSourceMap = new HashMap<String, String>();
	private static HashMap<String, EntityManagerFactory> emMap = new HashMap<String, EntityManagerFactory>();
	private static HashMap<String, Properties> propertyMap = new HashMap<String, Properties>();
	private static EntityManagerFactory emFactory;
	
	public static void addEMFactroy(String dataSource, Properties properties){
		if(!emMap.containsKey(dataSource)){
			propertyMap.put(dataSource, properties);
			emMap.put(dataSource, Persistence.createEntityManagerFactory("Default", properties));
		}
	}
	
	public static void addDataSource(String sessionId, String dataSource, Properties properties){
		dataSourceMap.put(sessionId, dataSource);
		addEMFactroy(dataSource, properties);
	}
	
	public static String getDataSource(String sessionId){
		return dataSourceMap.get(sessionId);
	}
	
	public static void deleteDataSource(String sessionId){
		dataSourceMap.remove(sessionId);
	}
	
	public static DBManager getDBManager(String sessionId) throws Exception
	{
		String l_ds = dataSourceMap.get(sessionId);
		Properties l_prop = propertyMap.get(l_ds);
		return new DBManager(l_prop.getProperty("hibernate.connection.driver_class"),
				l_prop.getProperty("hibernate.connection.url"),
				l_prop.getProperty("hibernate.connection.username"),
				l_prop.getProperty("hibernate.connection.password")
				);
	}
	
	public static EntityManager getEntityManager(String sessionId)throws Exception{
		return emMap.get(dataSourceMap.get(sessionId)).createEntityManager();
	}

	public static EntityManagerFactory getEmFactory() {
		return emFactory;
	}

	public static void setEmFactory(EntityManagerFactory emFactory) {
		DBManagerFactory.emFactory = emFactory;
	}
}
